package main

import (
	"fmt"
)

func factorial1(n int) int {
	if n < 0 {
		panic("n < 0")
	} else if n < 2 {
		return 1
	}
	result := 1
	for i := 1; i <= n; i++ {
		result *= i
	}
	return result
}

func factorial2(n int) int {
	if n < 0 {
		panic("n < 0")
	} else if n < 2 {
		return 1
	}
	return n * factorial2(n-1)
}

// n：计算的阶乘数量
// ret：初始值为1，为当前累积结果
// n=10 时计算：9!*10
// n=9  时计算：8!*9
func factorial3(n, ret int) int {
	if n < 0 {
		panic("n < 0")
	} else if n < 2 {
		return ret
	}

	return factorial3(n-1, ret*n)
}

func printTriangle(n int) {
	if n < 0 {
		panic("n < 0")
	}
	tmpStr := ""
	joinStr := " "

	// 获取最大宽度数值
	for i := 0; i < n+1; i++ {
		tmpStr += fmt.Sprintf("%d%s", i, joinStr)
	}
	maxLength := len(tmpStr)
	// fmt.Printf("maxLength: %v\n", maxLength)

	for i := 1; i <= n; i++ {
		stringRow := ""
		for j := i; j >= 1; j-- {
			// fmt.Print(j, joinStr)
			stringRow += fmt.Sprintf("%d%s", j, joinStr)
		}
		// fmt.Printf("%+30s\n", stringRow)
		fmt.Printf("%+[2]*[1]s\n", stringRow, maxLength)
	}
}

func main() {
	fmt.Println(factorial1(10))
	fmt.Println(factorial2(10))
	fmt.Println(factorial3(10, 1))
	printTriangle(20)

}
